package net.ufrog.common.spring.exception;

import net.ufrog.common.Result;
import net.ufrog.common.app.Validation;
import net.ufrog.common.exception.InvalidArgumentException;
import net.ufrog.common.utils.Strings;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import java.util.List;
import java.util.Map;

/**
 * @author ultrafrog, ufrog.net@gmail.com
 * @version 0.1, 2017-02-04
 * @since 0.1
 */
public class InvalidArgumentExceptionHandler implements ExceptionHandler<InvalidArgumentException> {

    @Override
    public Boolean isType(Exception e) {
        return e.getClass() == InvalidArgumentException.class;
    }

    @Override
    public ModelAndView handle(InvalidArgumentException e, String requestType, String errorView, String partViewSuffix, View jsonView, ExceptionLogger exceptionLogger) {
        Result<Map<String, List<Validation.Error>>> result = Result.failure(Validation.current().getErrorMap());
        if (Strings.equals(ExceptionResolver.REQUEST_TYPE_JSON, requestType)) {
            Validation.current().getAllErrors().forEach(error -> result.addMessage(error.getMessage()));
        }
        return ExceptionResolver.modelAndView(requestType, errorView, partViewSuffix, jsonView, ExceptionResolver.KEY_MODEL_EXCEPTION, result);
    }
}
